import { Button, Divider, Input, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CustomForm from '../../../components/CustomForm/index';
import { email } from '../../../services/api/system';
import HostField from './host-field';
const emailReg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;

export default function EmailConfig(props) {
  const [model, setModel] = useState({});
  const [disable, setDisable] = useState(true);
  const [loading, setLoading] = useState(false);
  useEffect(() => {
    email.getConfig().then((res) => {
      const config = res.data.email_config;
      if (config && Object.keys(config).length > 0) {
        setModel(config);
      } else {
        setModel({
          host: '',
          port: '',
          username: '',
          password: '',
        });
      }
    });
  }, []);
  const ref = useRef(null);
  const createForm = (form) => {
    ref.current = form;
  };
  const vad = () => {
    return new Promise((res, rej) => {
      ref.current.validateFields((err) => {
        err ? rej() : res();
      });
    });
  };
  const onTest = async (val) => {
    if (!val || !emailReg.test(val)) {
      return message.error('请输入正确的邮箱地址');
    }
    const close = message.loading('测试中，请稍后...');
    try {
      const { code, msg } = await email.test({
        email: val,
      });
      if (code !== 0) {
        message.error(msg);
      } else {
        message.success(msg || '发送成功');
      }
    } catch {}
    close();
  };
  const onSubmit = async () => {
    if (loading) {
      return;
    }
    await vad();
    const vals = ref.current.getFieldsValue();
    console.log(vals)
    setLoading(true);
    try {
      await email.setConfig({
        ...vals.host,
        password: vals.password,
        username: vals.username
      });
      message.success('保存成功');
      setDisable(true);
    } catch {
      //
    }
    setLoading(false);
  };
  const items = [
    {
      label: {
        label: '发送邮件服务器地址',
      },
      labelCol: 8,
      wrapperCol: 16,

      name: 'host',
      options: {
        initialValue: model,
        disabled: disable,
        rules: [
          {
            required: true,
          },
          {
            validator: (rule, vals, cb) => {
              if (!vals.host) {
                return cb('请输入地址');
              }
              if (!vals.port) {
                return cb('请输入端口');
              }
              cb();
            },
          },
        ],
      },

      component: <HostField disabled={disable} />,
    },
    {
      label: {
        label: '发送方姓名',
      },
      labelCol: 8,
      wrapperCol: 16,

      options: {
        initialValue: model.username,
        rules: [
          { required: true, message: '请输入发送方姓名' },
          { type: 'email', message: '邮箱格式错误' }
        ],
      },
      component: <Input disabled={disable} />,
      name: 'username',
    },
    {
      label: {
        label: '发送密码',
      },
      labelCol: 8,
      wrapperCol: 16,
      options: {
        initialValue: model.password,
        rules: [{ required: true, message: '请输入密码' }],
      },
      name: 'password',
      component: <Input type='password' disabled={disable} />,
    },
  ];
  if (Object.keys(model).length === 0) {
    return null;
  }
  return (
    <div style={{ background: '#fff' }}>
      <div style={{ width: '800px', margin: '20px auto', padding: '50px' }}>
        <CustomForm
          hideSubmit={true}
          loading={loading}
          colNum={1}
          formItems={items}
          createForm={createForm}
          onHandleSubmit={onSubmit}
        >
          <div style={{ textAlign: 'center' }}>
            {disable ? (
              <Button onClick={() => setDisable(false)} type='primary'>
                编辑
              </Button>
            ) : (
              <>
                <Button className='marr10' onClick={() => setDisable(true)}>
                  取消
                </Button>
                <Button htmlType='submit' type='primary'>
                  保存
                </Button>
              </>
            )}
          </div>
        </CustomForm>

        <Divider />
        <Input.Search disabled={!disable} placeholder='请输入邮箱地址' enterButton='测试' onSearch={onTest} />
      </div>
    </div>
  );
}
